using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using Microsoft.DirectX.AudioVideoPlayback;
using System.Collections;


namespace MusicTag
{
    public partial class MainWindow : Form
    {
        private Audio aud;
        String currentlyPlaying;
        int currentlyPlayingidx;
        //SortedDictionary<String, String> fullPath;
        Random r;
        bool ProgressChange;
        PlayList currentPlayList;

        public MainWindow()
        {
            InitializeComponent();
            ProgressChange = false;
            r = new Random();
            PlayListBox.ContextMenuStrip = PlayListCMenu;
            aud = null;
            currentlyPlaying = "";
            
            currentlyPlayingidx = -1;
            PlayListBox.Sorted = true;
            restoreLast();

        }

        ~MainWindow()
        {

            
        }



        private void restoreLast()
        {
            currentPlayList = new PlayList("last.pls");
            int i = 0;
            SortedDictionary<string, string>.KeyCollection keys = currentPlayList.GetKeys();
            foreach (string key in keys)
            {
                PlayListBox.Items.Add(key);
            }
            StatusLabel.Text = currentPlayList.getName();

        }

        private void clickExit(object sender, EventArgs e)
        {
            int i = 0;
            currentPlayList.Save("last.pls");

            this.Close();
        }

        private void clickOpenFile(object sender, EventArgs e)
        {
            
            OpenFileDialog fd = new OpenFileDialog();
            fd.ShowDialog();
            String file = fd.FileName.Substring(fd.FileName.LastIndexOf("\\") + 1);
            if (currentPlayList.exists(file) == false)
                currentPlayList.Add(file, fd.FileName);
            int idx = PlayListBox.Items.Add(file);
            PlayListBox.SelectedIndex = idx;
          
         
        }

        private void clickOpenDir(object sender, EventArgs e)
        {
            int i = 0;
            FolderBrowserDialog fd = new FolderBrowserDialog();
            fd.Description = "Get Music From a Folder...";
            fd.ShowNewFolderButton = false;
            
            DialogResult dres = fd.ShowDialog();
            if (dres.Equals(DialogResult.Cancel))
                StatusLabel.Text = "Cancelled.";
            else if(dres.Equals(DialogResult.OK))
            {
                DirectoryInfo di = new DirectoryInfo(fd.SelectedPath);


                FileInfo[] fimp3 = di.GetFiles("*.mp3");
                string val;
                for (i = 0; i < fimp3.Length; i++)
                {
                    try
                    {
                        if(currentPlayList.exists(fimp3[i].Name) == false)
                            currentPlayList.Add(fimp3[i].Name,fd.SelectedPath + "\\" + fimp3[i].Name);
                    }
                    catch (Exception)
                    {
                    }

                    PlayListBox.Items.Add(fimp3[i].Name);
                }



                FileInfo[] fiwma = di.GetFiles("*.wma");
                for (i = 0; i < fiwma.Length; i++)
                {
                    if (currentPlayList.exists(fiwma[i].Name) == false)
                        currentPlayList.Add(fiwma[i].Name, fd.SelectedPath + "\\" + fiwma[i].Name);
                    PlayListBox.Items.Add(fiwma[i].Name);

                }
            }


            
        }

        private void clickShuffle(object sender, EventArgs e)
        {
            //toggle shuffle
            shuffleToolStripMenuItem.Checked = !shuffleToolStripMenuItem.Checked;
        }

        private void clickRepeat(object sender, EventArgs e)
        {
            //toggle repeat
            repeatToolStripMenuItem.Checked = !repeatToolStripMenuItem.Checked;
        }

        private void clickAddSync(object sender, EventArgs e)
        {
            FolderBrowserDialog fd = new FolderBrowserDialog();
            fd.ShowDialog();
        }

        private void dropPlayListBox(object sender, DragEventArgs e)
        {
            //TODO: Add drag and drop support
            string[] types = e.Data.GetFormats();
            int i = 0;

            for (i = 0; i < types.Length; i++)
                PlayListBox.Items.Add(types[i]);
        }

        private void menuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {

        }

        private void InfoPanel_Paint(object sender, PaintEventArgs e)
        {

        }

        private void Play()
        {

            try
            {
                //if we're trying to play something that's invalid
                if ((currentlyPlayingidx == -1) || (currentlyPlayingidx > PlayListBox.Items.Count))
                {
                    if (PlayListBox.Items.Count == 0) return;
                    else currentlyPlayingidx = 0;
                }
                //play a new file
                if (currentlyPlaying != (String)PlayListBox.Items[currentlyPlayingidx])
                {
                    //set the new song to the currently selected idx
                    currentlyPlaying = (String)PlayListBox.Items[currentlyPlayingidx];
                    SongTitle.Text = currentlyPlaying;
                    //select this index in the listbox
                    PlayListBox.SelectedIndex = currentlyPlayingidx;
                    StatusLabel.Text = "Now Playing " + currentlyPlaying;
                    //find the full path map from the short name
                    string val = currentPlayList.GetValue(currentlyPlaying);
                    if (aud == null)
                    {
                        aud = new Audio(val, true);
                        //hook the next file function
                        aud.Ending += new System.EventHandler(SelectNextFile);
                        ProgressUpdateTimer.Enabled = true;
                        ProgressUpdateMover.Enabled = true;
                        SongProgressTrackBar.Value = 0;
                        SongProgressTrackBar.Maximum = (int)aud.Duration;
                    }
                    else
                    {
                        aud.Open(val, true);
                        aud.Play();
                        ProgressUpdateTimer.Enabled = true;
                        ProgressUpdateMover.Start();
                        SongProgressTrackBar.Value = 0;
                        SongProgressTrackBar.Maximum = (int)aud.Duration;
                    }
                }
                //restart a stopped file
                else if (aud.Paused)
                {
                    aud.Play();
                    ProgressUpdateTimer.Enabled = true;
                    ProgressUpdateMover.Start();
                }
                else
                {
                    aud.Stop();
                    aud.SeekCurrentPosition(0, SeekPositionFlags.AbsolutePositioning);
                    aud.Play();
                }
            }
            catch (Exception)
            {

            }


        }

        private void Next()
        {
            if (repeatToolStripMenuItem.Checked)
            {
                //play the same thing again
                Play();
            }
            else if (shuffleToolStripMenuItem.Checked)
            {
                //pick a random one and play it

                currentlyPlayingidx = r.Next() % PlayListBox.Items.Count;
                Play();
            }
            else
            {
                currentlyPlayingidx = (currentlyPlayingidx + 1) % PlayListBox.Items.Count;
                Play();
            }

        }

        private void Prev()
        {
            if ((repeatToolStripMenuItem.Checked)||(aud.CurrentPosition > 10))
            {
                //play the same thing again
                Play();
            }
            else if (shuffleToolStripMenuItem.Checked)
            {
                //pick a random one and play it

                currentlyPlayingidx = r.Next() % PlayListBox.Items.Count;
                Play();
            }
            else
            {
                currentlyPlayingidx = (currentlyPlayingidx - 1) % PlayListBox.Items.Count;
                Play();
            }

        }

        private void clickPlay(object sender, EventArgs e) 
        {
            currentlyPlayingidx = PlayListBox.SelectedIndex;

            Play();

        }

        private void clickStop(object sender, EventArgs e)
        {
            if (aud != null)
            {
                aud.Pause();
                ProgressUpdateTimer.Enabled = false;
                ProgressUpdateMover.Start();
            }
        }

        private void SelectNextFile(object sender, EventArgs e)
        {
            Next();
        }

        private void clickNext(object sender, EventArgs e)
        {
            Next();
        }

        private void clickPrev(object sender, EventArgs e)
        {
            Prev();
        }

        private void updateSongProgress(object sender, EventArgs e)
        {
            double current = aud.CurrentPosition;
            double total = aud.Duration;

            SongProgress.Text = SecondsToHMSString(current) + " / " + SecondsToHMSString(total);
            ProgressChange = true;
            SongProgressTrackBar.Value = (int) aud.CurrentPosition;
        }

        private string SecondsToHMSString(double secs)
        {
            string hours;
            string minutes;
            string seconds;

            hours = Convert.ToString((int)(secs / 3600));
            secs = secs - ((int)(3600 * Convert.ToDouble(hours)));
            minutes = Convert.ToString((int)(secs / 60));
            secs = secs - ((int)(60 * Convert.ToDouble(minutes)));
            seconds = Convert.ToString((int)secs);

            if (hours.Length < 2) hours = "0" + hours;
            if (minutes.Length < 2) minutes = "0" + minutes;
            if (seconds.Length < 2) seconds = "0" + seconds;


            return hours + ":" + minutes + ":" + seconds;

        }

        private void ProgressPanelMove(object sender, EventArgs e)
        {
            if ((aud.Playing) && (ProgressPanel.Location.Y > 300))
            {
                ProgressPanel.SetBounds(ProgressPanel.Location.X, ProgressPanel.Location.Y - 1, ProgressPanel.Width, ProgressPanel.Height);
                return;
            }
            else if ((aud.Paused) && (ProgressPanel.Location.Y < 324))
            {
                ProgressPanel.SetBounds(ProgressPanel.Location.X, ProgressPanel.Location.Y + 1, ProgressPanel.Width, ProgressPanel.Height);
                return;
            }
            else
            {
                ProgressUpdateMover.Stop();
            }
        }

        private void changeVolume(object sender, EventArgs e)
        {
            if (aud != null)
                aud.Volume = VolumeControl.Value;
            
        }

        private void clickMute(object sender, EventArgs e)
        {
            if (aud != null)
            {
                VolumeControl.Value = -10000;
                aud.Volume = VolumeControl.Value;
            }
        }

        private void keydownPlayList(object sender, KeyEventArgs e)
        {
            switch(e.KeyCode)
            {
                case Keys.Delete:
                    if(PlayListBox.SelectedIndex >= 0)
                        deleteSong();
                    break;

            }


        }

        private void deleteSong()
        {
            string song = (string)PlayListBox.Items[PlayListBox.SelectedIndex];
            int i = PlayListBox.SelectedIndex;
            StatusLabel.Text = song;
            if (currentPlayList.exists(song))
            {
                StatusLabel.Text += "\t" + i;
                currentPlayList.Remove(song);
                PlayListBox.Items.Remove(song);

            }
            if(i < PlayListBox.Items.Count)
                PlayListBox.SelectedIndex = i;

        }

        private void progressChanged(object sender, EventArgs e)
        {

        }

        private void clickAbout(object sender, EventArgs e)
        {

            AboutMusicTag amt = new AboutMusicTag();
            amt.ShowDialog();
            
        }


        private void clickRemove(object sender, EventArgs e)
        {
            deleteSong();
        }

        private void ProgressValueChanged(object sender, EventArgs e)
        {
            if (ProgressChange == true)
            {
                ProgressChange = false; return;
            }
            else
            {
                ProgressUpdateTimer.Stop();
                aud.SeekCurrentPosition(SongProgressTrackBar.Value * Math.Pow(10, 7), SeekPositionFlags.AbsolutePositioning);
                StatusLabel.Text = "Seeking to " + SongProgressTrackBar.Value + " ... " + aud.CurrentPosition;

                ProgressUpdateTimer.Start();
            }
        }
    }
}